import React, { useCallback, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { Button, LoadPanel, NumberBox, Popup, ProgressBar } from 'devextreme-react';
import { IColumnProps, Item, Paging, Toolbar } from "devextreme-react/data-grid";
import { DevGrid, LayoutB } from '~/public/cpas-ui';

import { useModel } from 'umi';
import { getExcelTableColumns, getNotExistsColumns } from '../tableColumnData';
import { AccountInfo, ExcelField, ExcelTable, ProgressInfo, SampleTable } from '../typing';
import { ROOTS } from '@/services/cpasRequest';
import { msgError } from '@/utils/msg';
import { downLocalFileArrayBuffer, getExcelFields, getExcelSourceColums, getExcelTableList, getExcelTableRowsData, getFieldSql, updateImportProgressInfo } from './samplingImportExcelService';
import { formatDateYYMMDD, getCpasPrimaryColor, getFullUserName, getGridDefaultPageProps, setDevOptions } from '@/utils/pub';
import { consts } from '../consts';
import CustomStore from "devextreme/data/custom_store";
import { LoadOptions } from 'devextreme/data';
import ReactDOM from 'react-dom';
import { inputQuery } from './tools/dialogs';
import getToken from '@/services/auth';
import { Progress } from 'antd';
import { devPopupTitleRendered } from './service';


/**
 * 样本源维护
 */

export const ImportExcelPupop = React.forwardRef((props: any, ref: any) => {
    const { initialState } = useModel('@@initialState');
    const { dbname, sjnd } = initialState?.curPart as any;
    const [visible, setVisible] = useState<boolean>(false);
    const [leftSlotWidth, setLeftSlotWidth] = useState<string>('300px');
    //样本源的表
    const [excelTableList, setExcelTableList] = useState<ExcelTable[]>([]);
    //样本源的数据
    const [excelSourceTableDataSource, setExcelSourceTableDataSource] = useState<CustomStore>();
    const [excelSourceDataColumns, setExcelSourceDataColumns] = useState<IColumnProps[]>([]);
    const [excelSourceFields, setExcelSourceFields] = useState<ExcelField[]>([]);
    const popupRef = useRef<any>();
    const devGridExcelTableRef = useRef<any>();
    const devGridExcelDataRef = useRef<any>();

    const startTimeRef = useRef<number>(); //开始时间
    const [progressInfo, setProgressInfo] = useState<ProgressInfo>({
        progressText: '',
        progressValue: 0,
    });
    //const [isNeedImportExcelPopup, setIsNeedImportExcelPopup] = useState<boolean>(false);

    //  const [pageIndex, setPageIndex] = useState<number>(0);
    //  const [pageSize, setPageSize] = useState<number>(consts.defaultSampePageSize);


    const [loading, setLoading] = useState<boolean>(false);
    const [importting, setImportting] = useState<boolean>(false);

    const [curExcelTable, setCurExcelTable] = useState<ExcelTable>();
    const [accountInfoList, setAccountInfoList] = useState<AccountInfo[]>([]);

    const [curDataId, setCurDataId] = useState<string>('');

    // const [titleRowNo, setTitleRowNo] = useState<number>(1);

    //Excel数据buffr
    const excelArrayBuffer = useRef<ArrayBuffer>()


    const diaParams = useRef<any>(null);
    // 自定义方法
    useImperativeHandle(ref, () => ({
        show: (params: any) => {
            diaParams.current = params;
            const { title, dataId, accountInfoList, excelFilePath } = params;
            setVisible(true);
            setCurExcelTable(undefined);
            setExcelSourceTableDataSource([] as any);
            setExcelTableList([]);

            setTimeout(async () => {
                setAccountInfoList(accountInfoList);
                setCurDataId(dataId);
                refreshLeftData(dataId);
            }, 800);

        },
    }));
    /**
     * 下载excel文件到
     * @returns
     */
    async function loadExcelArrayBuffer(): Promise<ArrayBuffer> {
        const arrayBuffer: ArrayBuffer = await downLocalFileArrayBuffer(diaParams.current.excelFilePath);
        return arrayBuffer;
    }
    /**
  * 获取样本表
  * @returns
  */
    const loadExcelSourceDataList = useCallback(async (/* pageIndex: number, pageSize: number, */
        excelTable: ExcelTable, excelSourceFields: ExcelField[], dataId: string) => {

        if (!excelTable?.tableName) return [];

        const tableRowsData = getExcelTableRowsData(excelTable, excelSourceFields);

        setExcelSourceTableDataSource(new CustomStore({
            key: 'rn',
            byKey: (key: any) => {
                return tableRowsData.find(item => item.rn === key);
            },
            load: async (loadOptions: LoadOptions) => {
                return {
                    data: tableRowsData,
                    totalCount: tableRowsData.length
                }
            }
        }));

        return tableRowsData;
    }, [curExcelTable, excelSourceFields,/*  pageIndex, pageSize, */ curDataId]);
    const onCancel = () => {
        diaParams.current.onCancel && diaParams.current.onCancel();

        //失败devGridExcelTable的所有数据
        let element = document.getElementById('leftContainer');
        element && ReactDOM.unmountComponentAtNode(element);
        element = document.getElementById('rightContainer');
        element && ReactDOM.unmountComponentAtNode(element);
        setVisible(false);
    }
    //加载样本源信息
    async function loadExcelSourceInfo(excelTable: ExcelTable, dataId: string) {
        try {
            const excelFields = getExcelFields(excelTable);
            const existsColumns = excelFields.length > 0;

            if (existsColumns) {
                loadExcelSourceDataList(excelTable, excelFields, dataId);
            } else {
                setExcelSourceTableDataSource([] as any)
            }

            let columns = getExcelSourceColums(excelFields.filter(item => item.visible));
            columns.forEach(item => {
                if (item.dataField == 'rn') {
                    item.caption = '表页行号';
                    item.dataField = consts.excelRowIndexFieldName;
                    item.width = 70
                }
            })

            columns = existsColumns ? columns : getNotExistsColumns(excelTable.tableTitle);

            setExcelSourceFields(excelFields);

            setExcelSourceDataColumns(columns);

            //  setLoading(false)
        }
        catch (error) {
            console.log(error)
            msgError(error)
        }
    }
    /**
     * 刷新左侧数据
     */
    async function refreshLeftData(dataId: string) {
        //加载表
        setLoading(true)
        setTimeout(async () => {
            excelArrayBuffer.current = await loadExcelArrayBuffer();
            const excelTableList = getExcelTableList(excelArrayBuffer.current, diaParams.current.maxOrdexIndex ?? 1
                ,diaParams.current.excelFilePath)
            if (excelTableList.length) {
                setExcelTableList(excelTableList);
                const excelTable = excelTableList[0];
                setDevOptions(devGridExcelTableRef, {
                    focusedRowKey: excelTable.guid,
                    selectedRowKeys: excelTableList.map(item => item.guid)
                })
                setCurExcelTable(excelTable);
                loadExcelSourceInfo(excelTable, dataId);
            } else {
                setCurExcelTable(undefined);
                setExcelTableList([]);
            }

            setLoading(false);

        }, 100);
    }

    //编辑
    const onEditClickOfTable = (e: any) => {

        if (!curExcelTable) {
            return msgError('还没有表名,请选择一个!')
        }

        //   console.log('onEditClickOfTable', sampleTale);
        const oldTableName = curExcelTable.tableName;
        let editing = false;
        inputQuery('', '', curExcelTable.tableTitle, async (newTableTitle: string) => {
            if (editing) return false;
            if (newTableTitle == oldTableName) {
                msgError('【' + newTableTitle + '】 名称未修改!')
                return false;
            }

            if (excelTableList.some(item => item.tableTitle == newTableTitle)) {
                msgError('【' + newTableTitle + '】名称重复!')
                return false;
            }
            editing = true;
            setTimeout(() => {//解决点击慢的问题

                const newTableName = oldTableName.replaceAll(curExcelTable.tableTitle, newTableTitle);

                devGridExcelTableRef.current.instance.cellValue(curExcelTable.rn - 1, 'tableTitle', newTableTitle)
                devGridExcelTableRef.current.instance.cellValue(curExcelTable.rn - 1, 'tableName', newTableName)
                devGridExcelTableRef.current.instance.saveEditData();

                editing = false;
            }, 10);


            return true;
        }, '', { zIndex: 2000 })

    }
    //执行导入
    async function executeImportExcel(): Promise<void> {

        const existsSampleTableList: SampleTable[] = diaParams.current.sampleTableList;

        const excelTableList: ExcelTable[] = devGridExcelTableRef.current.instance.getSelectedRowsData();

        if (excelTableList.length == 0) {
            return msgError('请选择要导入的表')
        }
        for (const excelTable of excelTableList) {
            if (existsSampleTableList.some(item => item.tableTitle == excelTable.tableTitle)) {
                return msgError(`【${excelTable.tableTitle}】已存在,不能重复导入!`)
            }
        }

        setImportting(true)

        const startTime = performance.now();
        startTimeRef.current = startTime;

        excelTableList.forEach(excelTable => {
            excelTable.excelFields = getExcelFields(excelTable);
            excelTable.tableRowsData = getExcelTableRowsData(excelTable, excelTable.excelFields);

            for (const excelField of excelTable.excelFields) {
                excelField.fieldSql = getFieldSql(excelField);
            }
            excelTable.sortFields = consts.orderIndexFieldName;//默认排序字段
        });


        const url = '/auditSample/executeImportExcel';
        const params = {
            dbname,
            excelTableList: excelTableList.map(item => ({ ...item, sheet: null })),
            userFullName: getFullUserName(initialState?.curUser?.usercode, initialState?.curUser?.username),
            dataId: curDataId,
        }

        //http进度提交
        await fetch(`${ROOTS}${url}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                cpasToken: getToken(),
            },
            body: JSON.stringify(params),
        }).then((response) => {
            return updateImportProgressInfo(response, setProgressInfo, (retData: API.SerResult) => {
                if (retData.ok) {
                    diaParams.current.onOk && diaParams.current.onOk(excelTableList);
                    setVisible(false);
                }
            });
        }).catch((error) => {
            msgError(error);
        });

        setImportting(false)

    }
    const leftContainer = useCallback(() => {
        return <div id="leftContainer" style={{ marginRight: "15px", height: "100%" }} >

            <DevGrid.MultipleCheckBox
                className={` PaperDevSortableGrid devHeadersCenter `}
                height={'100%'}
                width="100%"
                ref={devGridExcelTableRef}
                dataSource={excelTableList}
                keyExpr="guid"
                defaultColumns={getExcelTableColumns()}
                showBorders={true}
                showRowLines={true}
                isRemote={true}
                showColumnLines={true}
                allowColumnResizing={true}
                paging={{ enabled: false, }}
                loadPanel={{ enabled: false }}
                columnMinWidth={20}
                focusedRowEnabled={true}
                defaultFocusedRowIndex={0}
                columnAutoWidth={false}
                onRowClick={(e: any) => {
                    setCurExcelTable(e.data)
                    loadExcelSourceInfo(e.data, curDataId)
                }}
                headerFilter={{ texts: { ok: '确定' } }}
                disableFirstHeaderSearch={true}
                onCellPrepared={(e) => {
                    if (e.rowType == 'data' && e.data.tableName == curExcelTable?.tableName) {
                        e.cellElement.style.color = getCpasPrimaryColor()
                        e.cellElement.style.fontWeight = 'bold'
                    }
                }}

            >
                <Toolbar>
                    <Item location="before">
                        <Button icon='iconfont icon-refresh'
                            className='refreshButton_Style'
                            disabled={importting || loading}
                            text='刷新Excel表页'
                            onClick={() => refreshLeftData(curDataId)} />
                    </Item>
                    <Item location="after">
                        <Button icon='iconfont icon-rename-copy'
                            disabled={importting || loading}
                            className='editButton_Style' text='重命名'
                            hint='重命名表页' onClick={onEditClickOfTable} />
                    </Item>

                </Toolbar>



            </DevGrid.MultipleCheckBox>

        </div>

    }, [excelTableList, curDataId, curExcelTable])

    /**
     * 更新行信息
     * @param curExcelTable
     * @param fieldName
     * @param value
     */
    function updateTitleRowValue(curExcelTable: ExcelTable, fieldName: string, value: any) {

        (curExcelTable as any)[fieldName] = value;
        let dataRowCount = curExcelTable.endRowNo - curExcelTable.titleRowNo;
        if (dataRowCount < 0) {
            dataRowCount = 0;
        }
        devGridExcelTableRef.current.instance.cellValue(curExcelTable.rn - 1, fieldName, value);
        devGridExcelTableRef.current.instance.cellValue(curExcelTable.rn - 1, 'dataRowCount', dataRowCount)
    }

    function rightContainer() {
        // console.log('progressValue ,', progressInfo.progressValue);//不加这个不
        return <div id="rightContainer" style={{ marginLeft: 10, marginRight: "15px", height: "100%" }} >


            <DevGrid.MultipleTap
                className={` PaperDevSortableGrid devHeadersCenter `}
                height={'100%'}
                width="100%"
                id="devGriExcelSource"
                ref={devGridExcelDataRef}
                dataSource={excelSourceTableDataSource}
                keyExpr="rn"
                columns={excelSourceDataColumns}//不加这个,setExcelSourceDataColumns会导致这个报错
                isRemote={true}
                showBorders={true}
                showRowLines={true}
                showColumnLines={true}
                allowColumnResizing={true}
                loadPanel={{ enabled: true }}
                columnMinWidth={30}
                defaultFocusedRowIndex={0}
                searchPanel={{ visible: false, width: 100 }}
                headerFilter={{ texts: { ok: '确定' } }}
                disableFirstHeaderSearch={true}
                pager={getGridDefaultPageProps()}
                //focusedRowEnabled={true} 这个属性不能加,会导致数组分页的totalCount不生效
                remoteOperations={{ paging: false }} //加这个才能支持远程分页 本地过滤 20230507

                renderAsync={true}
                sheetName={curExcelTable?.tableTitle}
                excelName={curExcelTable?.tableTitle + '-' + formatDateYYMMDD(new Date())}

            >
                <Paging
                    enabled={true}
                    defaultPageSize={consts.defaultSampePageSize}
                />
                {useMemo(() => {

                    let progressVisible = progressInfo.progressValue > 0 && progressInfo.progressValue <= 100;
                    const startTime = startTimeRef.current ?? performance.now();
                    const takeSeconds = '耗时' + ((performance.now() - startTime) / 1000).toFixed(0) + '秒';
                    const progressText = `已完成 ${(progressInfo.progressValue).toFixed(0)}% ${takeSeconds}　${progressInfo.progressText} `;
                    return <Toolbar >
                        <Item location='before' >
                            <div style={{ width: 450, marginTop: -10, display: progressVisible ? '' : 'none' }}>
                                <Progress
                                    type="line"
                                    percent={progressInfo.progressValue}
                                    showInfo={true}
                                    size="default"
                                    strokeColor={getCpasPrimaryColor()}
                                    status="active"
                                    style={{
                                        width: '100%',
                                        zIndex: 10,
                                        marginLeft: 5,
                                        marginRight: 5,
                                        minWidth: 300,
                                    }}
                                />
                                <div style={{ marginLeft: 5 }}>{progressText}</div>
                            </div>
                        </Item>

                        <Item location='before' locateInMenu={'auto'} >
                            <div style={{
                                marginLeft: 10, color: getCpasPrimaryColor(),
                                display: progressVisible ? 'none' : ''
                            }}>注：Excel表标题行不能有合并单元格</div>
                        </Item>
                        <Item location={progressVisible ? 'before' : 'after'} >
                            <div style={{ marginLeft: 10, color: getCpasPrimaryColor(), display: progressVisible ? 'none' : '' }}>
                                {curExcelTable ? `【${curExcelTable.tableTitle}】 共 ${curExcelTable.totalCount} 行` : ''}
                            </div>
                        </Item>
                        <Item location='after' >
                            <div style={{ marginLeft: 10, display: 'flex', alignItems: 'center' }}>
                                标题行：<NumberBox width={70} showSpinButtons={true} max={100} min={1}
                                    value={curExcelTable?.titleRowNo}
                                    hint={curExcelTable?.titleRowNo + ''}
                                    disabled={importting || loading}
                                    onValueChanged={(e: any) => {
                                        if (curExcelTable) {
                                            updateTitleRowValue(curExcelTable, 'titleRowNo', e.value);
                                            loadExcelSourceInfo(curExcelTable, curDataId);
                                        }
                                    }}
                                />
                            </div>

                        </Item>
                        <Item location='after' >
                            <div style={{ marginLeft: 10, display: 'flex', alignItems: 'center' }}>
                                结束行：<NumberBox width={120}
                                    showSpinButtons={true}
                                    value={curExcelTable?.endRowNo}
                                    hint={curExcelTable?.endRowNo + ''}
                                    max={curExcelTable?.totalCount}
                                    disabled={importting || loading}
                                    onValueChanged={(e: any) => {
                                        if (curExcelTable) {
                                            updateTitleRowValue(curExcelTable, 'endRowNo', e.value);
                                            loadExcelSourceInfo(curExcelTable, curDataId);
                                        }
                                    }}
                                />
                            </div>
                        </Item>
                        <Item location='after'>
                            <Button type='default' icon='iconfont icon-queren' text='执行导入'
                                disabled={importting || loading} onClick={() => executeImportExcel()}></Button>
                        </Item>

                    </Toolbar>

                }, [curExcelTable, curDataId, curExcelTable?.titleRowNo, curExcelTable?.endRowNo,
                    loading, progressInfo, importting])
                }
            </DevGrid.MultipleTap>
        </div >
    }


    return (
        <>
            <Popup
                ref={popupRef}
                visible={visible}
                disabled={loading}
                title={'导入Excel表 ' + (diaParams.current?.excelFilePath || '')}
                //  onTitleRendered={(e) => { devPopupTitleRendered(e) }} //解决 dx-popup 标题有....的问题
                width={'95vw'}
                height={'90vh'}
                onHiding={() => { onCancel() }}
            // disabled={loading}
            >
                <div id='mainDiv' style={{ height: '100%', width: '100%', overflow: 'hidden' }}  >

                    <LayoutB
                        rowSize={["300px", "300px"]}
                        leftSlot={leftContainer()}
                        rightSlot={rightContainer()}
                        layoutRowChange={(args: any) => {
                            setLeftSlotWidth(args[0]);
                        }}
                    />
                </div>
                {/* <ProgressBar
                    style={{ marginTop: '2px', position: 'absolute', top: 70, left: 40 + Number(leftSlotWidth.replace('px', '')), zIndex: 1 }}
                    visible={progressVisible}
                    width={350}
                    height={35}
                    value={progressInfo.progressValue}
                    showStatus={true}
                    min={0}
                    max={100}
                    statusFormat={(ratio: number, value: number) => {
                        const startTime = startTimeRef.current ?? performance.now();
                        const takeSeconds = '耗时' + ((performance.now() - startTime) / 1000).toFixed(0) + '秒';

                        return `已完成 ${(ratio * 100).toFixed(0)}% ${takeSeconds}　${progressInfo.progressText} `;
                    }}
                /> */}
            </Popup >
            <LoadPanel visible={loading} />

        </>
    );
});
